#!/usr/bin/env python3
#coding:utf-8

__author__ = 'xmxoxo<xmxoxo@qq.com>'

'''
从摄像头视频中识别人脸
'''

import cv2
import dlib

print('正在加载人脸检测模型...')
# Load the detector
detector = dlib.get_frontal_face_detector()
# Load the predictor
predictor = dlib.shape_predictor("face_models/shape_predictor_68_face_landmarks.dat")

# read the image
print('正在启动摄像头...')
cap = cv2.VideoCapture(0)
while True:
    _, frame = cap.read()
    frame = frame[::-1].copy()
    # Convert image into grayscale
    gray = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY)
    # Use detector to find landmarks
    faces = detector(gray)
    for face in faces:
        x1 = face.left()
        # left point
        y1 = face.top()
        # top point
        x2 = face.right()
        # right point
        y2 = face.bottom()
        # draw rectangle
        cv2.rectangle(frame,(x1, y1), (x2, y2), (255, 0, 255), 1)

        # bottom point
        # Create landmark object
        landmarks = predictor(image=gray, box=face)
        # Loop through all the points 画出人脸所有关键点 共69个
        for n in range(0, 68):
            x = landmarks.part(n).x
            y = landmarks.part(n).y
            # Draw a circle
            cv2.circle(img=frame, center=(x, y), radius=2, color=(0, 255, 0), thickness=-1)

    # show the image
    cv2.imshow(winname="Face", mat=frame)
    # Exit when escape is pressed
    if cv2.waitKey(delay=1) == 27:
        break

# When everything done, release the video capture and video write objects
cap.release()
# Close all windows
cv2.destroyAllWindows()


if __name__ == '__main__':
    pass

